<template>
  <div class="userData">
    <div class="user-box">
      <div class="publish-flex">
        <el-button type="warning" @click="addShop" style="margin-bottom: 20px">挂售商品</el-button>
        <el-button type="warning" @click="addType" style="margin-bottom: 20px">增加分类</el-button>
      </div>
       
    <el-table size="small" :data="shopList" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;" max-height="400">
      <el-table-column align="center" prop="goodsName" label="商品昵称" width="150">
      </el-table-column>
      <el-table-column align="center" prop="coverImg" label="商品封面图片" width="150">
        <template slot-scope="scope" v-if="scope.row.coverImg">
          <el-image
            style="width: 100px"
            :src="scope.row.coverImg"
            fit="contain"></el-image>
        </template>
      </el-table-column>
      <!-- <el-table-column  align="center" prop="originalPrice" label="原价(进货价)" width="150">
      </el-table-column> -->
      <el-table-column  align="center" prop="price" label="售卖价（元）" width="150">
      </el-table-column>
      <!-- <el-table-column  align="center" prop="typeName" label="类型" width="150">
      </el-table-column> -->
      <el-table-column  align="center" prop="describes" label="挂售描述" width="150">
      </el-table-column>
      <el-table-column  align="center" prop="amount" label="商品数量" width="150">
      </el-table-column>
      <!-- <el-table-column  align="center" prop="isSell" label="商品状态" width="150">
        <template slot-scope="scope">
          {{scope.row.isSell ? '已上架' : '已下架'}}
        </template>
      </el-table-column> -->
      <el-table-column align="center" label="操作" min-width="300">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="warning" @click="lookSellGood(scope.$index, scope.row)">售卖记录</el-button> -->
          <el-button size="mini" type="danger" @click="deleteShop(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 编辑界面 -->
    <el-dialog title="挂售商品" :visible.sync="editFormVisible" width="40%" @click="closeDialog">
      <el-form label-width="120px" :model="editForm" :rules="rules" ref="editForm">
        <el-form-item label="商品名称" prop="goodsName">
          <el-input size="small" v-model="editForm.goodsName" auto-complete="off" placeholder="请输入商品昵称"></el-input>
        </el-form-item>
        <el-form-item label="商品封面图片" prop="coverImg">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-change="handleChange"
            :auto-upload="false"
            :before-upload="beforeAvatarUpload">
            <img v-if="editForm.coverImg" :src="editForm.coverImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      <el-form-item label="分类名称" prop="typeId">
        <el-select v-model="editForm.typeId" clearable placeholder="请选择分类名称">
          <el-option :label="item.label" :value="item.value" v-for="item in typeList" :key="item.value"></el-option>
        </el-select>
      </el-form-item>
        <!-- <el-form-item label="原价(进货价)" prop="originalPrice">
          <el-input size="small" v-model="editForm.originalPrice" auto-complete="off" placeholder="请输入原价"></el-input>
        </el-form-item> -->
        <el-form-item label="售卖价（元）" prop="price">
          <el-input size="small" v-model="editForm.price" auto-complete="off" placeholder="请输入售卖价（元）"></el-input>
        </el-form-item>
        <el-form-item label="挂售描述" prop="describes">
          <el-input size="small" v-model="editForm.describes" auto-complete="off" placeholder="请输入挂售描述"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="amount">
          <el-input size="small" v-model="editForm.amount" auto-complete="off" placeholder="请输入商品数量"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button size="small" @click="closeDialog">取消</el-button> -->
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog title="售卖记录" :visible.sync="showSell" width="60%" @click="closeSell">
      <el-table size="small" :data="sellList"  border style="width: 90%;margin: 0 auto" max-height="400">
        <el-table-column align="center" prop="goodsSerialNumber" label="商品编号" width="160">
        </el-table-column>
        <el-table-column align="center" prop="consigneeName" label="买家昵称" width="180">
        </el-table-column>
        <el-table-column align="center" prop="consigneeAddress" label="买家地址" width="180">
        </el-table-column>
        <el-table-column align="center" prop="amount" label="购买数量" width="180">
        </el-table-column>
        <el-table-column align="center" prop="totalMoney" label="支付总额" width="180">
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="增加商品分类" :visible.sync="typeDialog" width="60%" @click="typeDialog=false">
      <el-form label-width="120px">
        <el-form-item label="分类名">
          <el-input size="small" v-model="typeName" auto-complete="off" placeholder="请输入分类名"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button size="small" @click="typeDialog=false">取消</el-button> -->
        <el-button size="small" type="primary"  @click="sureType">保存</el-button>
      </div>
    </el-dialog>
    </div>
  </div>
</template>
<script>
import { mapMutations, mapState } from 'vuex'
export default {
  name: 'Publish',
   data () {
    return {
      typeDialog: false,
      typeName: '',
      sellList: [], // 售卖列表
      typeList: [], // 分类列表
      shopList: [], //商品列表
      pageQuery: {
        pageNum: 1,
        pageSize: -1
      },
      listQuery: {
        userId: '',
        pageNum: 1,
        pageSize: -1
      },
      loading: false, //是显示加载
      showSell: false,
      editFormVisible: false, // 编辑框是否弹出
      editForm: {
        id: '',
        userId: '',
        typeId: '',
        goodsName: '',
        coverImg: '',
        // originalPrice: '',
        price: '',
        describes: '',
        amount: ''
      },
      // rules表单验证
      rules: {
        goodsName: [
          { required: true, message: '请输入商品昵称', trigger: 'blur' }
        ],
        // originalPrice: [{ required: true, message: '请输入原价', trigger: 'blur' }],
        price: [{ required: true, validator: (rule, value, callback) => {
      const age= /^[0-9]*$/
      if (!age.test(value)) {
        callback(new Error('价格只能为数字'))
      }else{
        callback()
      }
    }, trigger: 'blur' }],
        describes: [{ required: true, message: '请输入挂售描述', trigger: 'blur' }],
        amount: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        typeId: [{ required: true, message: '请选择分类', trigger: 'change' }]
      }
    }
  },
  created () {
    this.getShopList()
    this.getType()
  },
  computed: {
    ...mapState(['user'])
  },
  methods: {
    ...mapMutations(['saveUser']),
    addType () {
      this.typeDialog = true
    },
    sureType () {
      let params = {
        typeName: this.typeName
      }
      this.$api.shop.addType(params).then(res => {
        if (res.code === 200) {
          this.typeDialog = false
          this.typeName = ''
          this.getType()
        }
      })
    },
    getType () {
      this.$api.shop.getVarityList(this.pageQuery).then(res => {
        if (res.code === 200) {
          this.typeList = res.data.records.map(item => {
            return {
              label: item.typeName,
              value: item.id
            }
          })
        }
      })
    },
    /**
     * 关掉售卖记录框
     */
    closeSell () {
      this.showSell = false
    },
    /**
     * 编辑弹框保存商品修改信息
     */
    submitForm () {
        this.editForm.userId = this.user.id
        delete this.editForm.id
        this.$api.shop.addShop(this.editForm).then(res => {
          if (res.code === 200) {
            this.editFormVisible = false
            this.getShopList()
          }
        })
    },
    /**
     * 获取商品列表
     */
    getShopList() {
      this.loading = true
      this.listQuery.userId = this.user.id
      this.$api.shop.getGoodsByUser(this.listQuery).then(res => {
        if (res.code === 200) {
          this.shopList = res.data.records
          this.loading = false
        }
      }).catch(err => this.loading = false)
    },
    /**
     * 关闭编辑、增加弹出框
     */
    closeDialog() {
      this.editFormVisible = false
    },
    /**
     * 对货品上下架
     */
    changeGood (shop) {
      let params = {
        id: shop.id,
        isSell: Number(!shop.isSell)
      }
      this.$api.shop.controlShop(params).then(res => {
        if (res.code === 200) {
          this.getShopList()
        }
      })
    },
    /**
     * 增加商品
     */
    addShop () {
      this.editFormVisible = true
      // this.editForm.userId = this.user.id
      this.editForm.typeId = ''
      this.editForm.goodsName = ''
      this.editForm.coverImg = ''
      // this.editForm.originalPrice = ''
      this.editForm.price = ''
      this.editForm.describes = ''
      this.editForm.amount = ''
    },
    /**
     * 查看售卖列表
     */
    lookSellGood (index, sell) {
      this.showSell = true
      let query = {
        userId: this.user.id
      }
      this.$api.shop.lookSellGood(query).then(res => {
        if (res.code === 200) {
          this.sellList = res.data
        }
      })
    },
    /**
     * 删除商品
     */
    deleteShop (index, shop) {
      this.$api.shop.deleteShop({id:shop.id}).then(res => {
        if (res.code === 200) {
          this.getShopList()
        }
      })
    },
    handleAvatarSuccess(res, file) {
      this.editForm.coverImg = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传商品封面图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
    /****
     * 上传图片 起步函数
     */
    handleChange (file) {
      this.submitUpload(file)
    },
    /***
     * 上传图片 上传函数
     */
    submitUpload (file) {
        let formData = new FormData() //  用FormData存放上传文件
        formData.append('file', file.raw, file.raw.name)
        this.$api.auth.uploadImage(formData).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '上传成功!'
            })
            this.editForm.coverImg = res.data
          }
        })
    },
  }
}
</script>
<style lang="scss" scoped>
.userData {
  .user-box{
    width:90%;
    margin:20px auto;
    .publish-flex{
      display: flex;
      flex-flow: row nowrap;
      align-items: center;
      justify-content: space-between;
    }
    .user-color{
      color: #ff6600;
      font-size: 18px;
    }
  }
  .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
}
</style>
